package org.brisling.satisfaction.queryService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.util.DateUtil;
import org.brisling.satisfaction.domain.BaseSatisfactionInfo;
import org.brisling.satisfaction.domain.VOSatisfaction;
import org.brisling.satisfaction.domain.VOSatisfactionWindow;
import org.brisling.satisfaction.service.SatisfactionBaseinfoService;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
/**
 * 
 * <p>Title: QuerySatisBaseinfoService</p>
 * <p>Description: 满意度基本信息查询服务</p>
 * <p>Company: tongking </p>
 * @author jackson wang
 * @since  1.0
 * @version 1.0
 * @date 2016年6月20日 下午9:07:30
 */
@RestController
@RequestMapping("/satisfactionBaseinfo/query")
public class QuerySatisBaseinfoService extends AbstractBaseQueryService<BaseSatisfactionInfo>{
	
	@Autowired
	private SatisfactionBaseinfoService infoService;
	
	@Autowired
	private QueryDictionaryService qryDictionaryService;
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;	
	
	@Autowired
	private QuerySatisEvaluateHisService qrySatisEvaluateHisService;
	
	private static final String BIZ_QUERY_ALL = "query_satisfaction_all";
	
	
	public QuerySatisBaseinfoService(){
		this.moduleName = ConstSysParam.MODULE_SATISFACTION_BASE_INFO;
		this.subSystem = ConstSysParam.SUBSYSTEM_STATISFACTION;
		this.tableName = this.moduleName;
		this.clazz = BaseSatisfactionInfo.class;
		typeMap = this.getTypeMap(clazz);
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/popPage.action")
	public ModelAndView getPopPage(){
		String userid = shiroSecurityService.getCurrentUserIdentify();
		String _page = "popMain";
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL,BIZ_QUERY_ALL)){
			if(!isManageJob(userid)){				
				_page="popDetail";
			}					
		}
		return new ModelAndView("/medical/medical_base_medicals/"+_page);
	}
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<BaseSatisfactionInfo> getListDomain(@RequestBody(required=false) String body){		
		
		
		//查询表
		return super.getListDomainByConditionAndOrder(null, body, typeMap, orderMap, true);
		
		
	}
	
//	@RequestMapping("/getListDomain.action")
//	public ListDomain<BaseSatisfactionInfo> getListDomain(@RequestBody(required=false) String body){		
//		
//		
//		//查询表
//		ListDomain<BaseSatisfactionInfo> map1 = new ListDomain<BaseSatisfactionInfo>();
//		List<BaseSatisfactionInfo> rows = new ArrayList<BaseSatisfactionInfo>();
//		BaseSatisfactionInfo e = new BaseSatisfactionInfo();
//		e.setSatisfied_window_num(1L);
//		e.setOutinpatient_problem_num(1L);
//		e.setInpatient_dept_num(1L);
//		e.setInpatient_problem_num(1L);
//		e.setWindow_percent(0.12);
//		e.setOutinpatient_problem_percent(0.12);
//		e.setInpatient_dept_percent(0.12);
//		e.setInpatient_problem_percent(0.12);
//		rows.add(e);
//		map1.setRows(rows);
//		
//		return map1;
//		
//	}
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	@RequestMapping("/getDeptListDomain.action")
	public ListDomain<BaseSatisfactionInfo> getDeptListDomain(@RequestBody(required=false) String body){	
		
		
		Map<String,Object> map = this.getBodyParam(body);
		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, BIZ_QUERY_ALL)){
			if(isManageJob(userid)){
				addJobDeptConditionToMap(userid,map,"dept_code_in");
			}else{
				addUsridConditionToMap(userid,map,"doct_code");
			}
			//查找科室数据		
		}
		
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		if(!paramMap.containsKey("data_type"))
			paramMap.put("data_type", "1");
		
		if(!paramMap.containsKey("patient_type"))
			paramMap.put("patient_type", "1");
		
		map.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);		
		
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
	}
	
	@RequestMapping("/getAllListDomain.action")
	public ListDomain<BaseSatisfactionInfo> getAllListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, BIZ_QUERY_ALL)){
			if(isManageJob(userid)){
				String deptids = this.getJobDeptidAndAccountDeptids(userid);
				paramMap.put("dept_code_in", deptids);
			}else{
				paramMap.put("doct_code", userid);					
			}
			//查找科室数据		
		}else{
			paramMap.put("dept_code_in", "-1");
		}
		
		map.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);		
		
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
	}
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	
	private List<BaseSatisfactionInfo> getList(String monitor_year_month){
		
		String sql = String.format("select * from %1$s where monitor_year_month='%2$s'",this.tableName,monitor_year_month); 
		//查询表
		return super.getAllList(sql);
		
	}
	
	/**
	 * 查询实时数据
	 * @param body
	 * @return
	 */
	@RequestMapping("/getRealTimeListDomain.action")
	public ListDomain<BaseSatisfactionInfo> getRealTimeListDomain(@RequestBody(required=false) String body){		
		Map<String,Object> paramMap = this.getBodyParam(body);
		
		String[] monitorDate = super.getMonitorDate(paramMap);
		if(monitorDate!=null && monitorDate.length>1){			
			
			String start = monitorDate[0];
			String end = monitorDate[1];
			String year_month = monitorDate[2];
			List<BaseSatisfactionInfo> inlists =countBaseMedicalInpatient (year_month,start,end);
			List<BaseSatisfactionInfo> outlists =countBaseMedicalOutpatient(year_month,start, end);
			
			if(inlists!=null || outlists!=null){
				inlists.addAll(outlists);
				infoService.save(inlists);
				
				return super.getListDomainByConditionAndOrderUseTable(body, typeMap, orderMap,true);
			}					
			
		}
		//查询表
		
		return new ListDomain<BaseSatisfactionInfo>();
	}
	
	
	public void autoTask(Integer year,Integer month){
		this.autoMonitor(year, month);
//		this.autoUpdateStandard(year, month);
	}
	/**
	 * 执行自动统计
	 */
	public void autoMonitor(Integer year,Integer month){
		String[] yestodayMonth = null;
		if(year ==null || month ==null)
			yestodayMonth = DateUtil.getYestodayMonthDay();
		else{
			yestodayMonth = DateUtil.getMonthDay(year, month);
		}
		
		//获取窗口满意度数据
		VOSatisfactionWindow windowData =getWindowNumAndPercent(yestodayMonth[0],yestodayMonth[1]);
		
		//获取窗口问卷满意率数据
		VOSatisfaction windowProblemData =getWindowProblemAndPercent(yestodayMonth[0],yestodayMonth[1]);
		
		//获取窗口满意度数据
		VOSatisfaction inpatientDeptData =getinpatientDeptAndPercent(yestodayMonth[0],yestodayMonth[1]);
		
		//获取窗口问卷满意率数据
		VOSatisfaction inpatientProblemData =getinpatientProblemAndPercent(yestodayMonth[0],yestodayMonth[1]);
				
		BaseSatisfactionInfo bi = new BaseSatisfactionInfo();
		
		//查询已有数据
		List<BaseSatisfactionInfo> oldLists = this.getList(yestodayMonth[2]);
		
		//将已有值存入临时map
		if(oldLists!=null && oldLists.size()>0){
			bi = oldLists.get(0);
			
		}else{
			bi = new BaseSatisfactionInfo();
		}
		
		bi.setMonitor_year_month(yestodayMonth[2]);
		//窗口满意率
		bi.setSatisfied_window_num(windowData.getCnt()!=null?windowData.getCnt():0);
		bi.setWindow_percent(windowData.getSatisfy_rate()!=null?windowData.getSatisfy_rate():0.0);
		
		//门诊问卷满意率
		bi.setOutinpatient_problem_num(windowProblemData.getCnt()!=null?windowProblemData.getCnt():0);
		bi.setOutinpatient_problem_percent(windowProblemData.getMyl()!=null?Double.parseDouble(windowProblemData.getMyl()):0.0);
		
		//住院科室满意率
		bi.setInpatient_dept_num(inpatientDeptData.getCnt()!=null?inpatientDeptData.getCnt():0);
		bi.setInpatient_dept_percent(inpatientDeptData.getMyl()!=null?Double.parseDouble(inpatientDeptData.getMyl()):0.0);
		
		//住院问卷满意率
		bi.setInpatient_problem_num(inpatientProblemData.getCnt()!=null?inpatientProblemData.getCnt():0);
		bi.setInpatient_problem_percent(inpatientProblemData.getMyl()!=null?Double.parseDouble(inpatientProblemData.getMyl()):0.0);
		
		
		Double _myl = (bi.getWindow_percent()+bi.getOutinpatient_problem_percent()+bi.getInpatient_dept_percent()+bi.getInpatient_problem_percent())/4;
		
		HashMap<String, String> paramMap = SysConfig.getMaps();
		if(paramMap !=null){
			if(paramMap.containsKey("myl_formula")){
				String mf = paramMap.get("myl_formula");
				if(mf.compareTo("outpatient")==0){
					 _myl = (bi.getWindow_percent()+bi.getOutinpatient_problem_percent())/2;
					
				}
			}
		}
		bi.setMyl(_myl);
		infoService.save(bi);		
			
	}
	
	public void autoUpdateStandard(Integer year,Integer month){
		String[] yestodayMonth = null;
		if(year ==null || month ==null)
			yestodayMonth = DateUtil.getYestodayMonthDay();
		else{
			yestodayMonth = DateUtil.getMonthDay(year, month);
		}
		infoService.updateStandard(yestodayMonth[2]);
	}
	
	
	/**
	 * 查询窗口满意度及评价数量
	 * @return
	 */
	
	private VOSatisfactionWindow getWindowNumAndPercent(String start_date, String end_date){
		
		
		Map<String,String> retmap = new HashMap<String,String>();
		String whereCorse = String.format(" where pjsj >= to_date('%1$s 00:00:00','yyyy-MM-dd hh24:mi:ss') and pjsj <=to_date('%2$s 00:00:00','yyyy-MM-dd hh24:mi:ss') ",start_date,end_date);
		String sql = String.format(qryDictionaryService.getSqlByBizcode("window_evaluate_all"),whereCorse);
		
		
				
		retmap = super.getSingleRecord(sql);
		
		return reflectClassedMap(VOSatisfactionWindow.class,retmap);
	}
	
	/**
	 * 查询门诊问卷满意度及评价数量
	 * @return
	 */
	
	private VOSatisfaction getWindowProblemAndPercent(String start_date, String end_date){
		
		
		HashMap<String,String> retmap = new HashMap<String,String>();
		String whereCorse = String.format(" where evaluate_time >= to_date('%1$s 00:00:00','yyyy-MM-dd hh24:mi:ss') and evaluate_time <=to_date('%2$s 00:00:00','yyyy-MM-dd hh24:mi:ss') and type = 1 ",start_date,end_date);
		String sql = String.format(qryDictionaryService.getSqlByBizcode("window_problem_all"),whereCorse);
		
		
//		String whereCorse = String.format(" evaluate_time >= to_date('%1$s 00:00:00','yyyy-MM-dd hh24:mi:ss') and evaluate_time <=to_date('%2$s 00:00:00','yyyy-MM-dd hh24:mi:ss') ",start_date,end_date);
//		String userid = shiroSecurityService.getCurrentUserIdentify();
//		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, this.BIZ_QUERY_ALL)){
//			if(isManageJob(userid)){
//				String deptids = super.getJobDeptids(userid);
//				
//				if(deptids!=null && deptids.trim().length()>0)
//				whereCorse	+= String.format(" and deptid in (%1$s)",deptids);
//				retmap = super.getMappedList(sql);
//				
//			}		
//			//查找科室数据		
//		}
		
		retmap = super.getSingleRecord(sql);
		return reflectClassedMap(VOSatisfaction.class,retmap);
	}
	
	
	/**
	 * 查询门诊问卷满意度及评价数量
	 * @return
	 */
	
	private VOSatisfaction getinpatientDeptAndPercent(String start_date, String end_date){		
		
		Map<String,String> retmap = new HashMap<String,String>();	
		
		String whereCorse = String.format(" where evaluate_time >= to_date('%1$s 00:00:00','yyyy-MM-dd hh24:mi:ss') and evaluate_time <=to_date('%2$s 00:00:00','yyyy-MM-dd hh24:mi:ss') and evaluate_type = 2 ",start_date,end_date);
		String sql = String.format(qryDictionaryService.getSqlByBizcode("inpatient_dept_all"),whereCorse);
		retmap = super.getSingleRecord(sql);
		return reflectClassedMap(VOSatisfaction.class,retmap);
	}
	/**
	 * 查询门诊问卷满意度及评价数量
	 * @return
	 */
	
	private VOSatisfaction getinpatientProblemAndPercent(String start_date, String end_date){		
		
		Map<String,String> retmap = new HashMap<String,String>();
		String whereCorse = String.format(" where evaluate_time >= to_date('%1$s 00:00:00','yyyy-MM-dd hh24:mi:ss') and evaluate_time <=to_date('%2$s 00:00:00','yyyy-MM-dd hh24:mi:ss') and evaluate_type = 2 ",start_date,end_date);
		String sql = String.format(qryDictionaryService.getSqlByBizcode("inpatient_problem_all"),whereCorse);
		retmap = super.getSingleRecord(sql);
		return reflectClassedMap(VOSatisfaction.class,retmap);
	}
	
	
	
	/**
	 * 统计基本药物住院缓存信息
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public List<BaseSatisfactionInfo> countBaseMedicalInpatient(String year_month,String startDate ,String endDate){
		
			
		
		String[] sqlids = {"base_medical_all_inpatient","base_medical_dept_inpatient","base_medical_doct_inpatient"};
		//统计全院数据-住院		
		List<String> sqls = new ArrayList<String>();
		for(int i = 0;i<sqlids.length;i++){
			String sql = qryDictionaryService.getSqlByBizcode(sqlids[i]);
			if(sql!=null){
				sqls.add(sql);
			}
		}
		//所有数据
		List<BaseSatisfactionInfo> lists = super.monitorCountBase(year_month,startDate,endDate,sqls);		
		
		return lists;
		
	}
	
	/**
	 * 统计基本药物门诊缓存信息
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public List<BaseSatisfactionInfo> countBaseMedicalOutpatient(String year_month,String startDate ,String endDate){		
			
		
		String[] sqlids = {"base_medical_all_outpatient","base_medical_dept_outpatient","base_medical_doct_outpatient"};
		//统计全院数据-住院		
		List<String> sqls = new ArrayList<String>();
		for(int i = 0;i<sqlids.length;i++){
			String sql = qryDictionaryService.getSqlByBizcode(sqlids[i]);
			if(sql!=null){
				sqls.add(sql);
			}
		}
		//所有数据
		return super.monitorCountBase(year_month,startDate,endDate,sqls);	
		
	}
	
	
	
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public BaseSatisfactionInfo getOne(@RequestParam(value="id",required=false) Long id){
				
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public BaseSatisfactionInfo getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}
	
	
}
